<template>
    <view class="course-video-container">
        <!-- 顶部导航 -->
        <view class="nav-bar">
            <view class="nav-left" @click="goBack">
                <text class="iconfont icon-fanhui"></text>
            </view>
            <view class="nav-title">{{courseInfo.title || '课程视频'}}</view>
        </view>
        
        <!-- 视频播放器 -->
        <view class="video-player-container" v-if="currentVideo">
            <video 
                :id="'video-player-' + (currentVideo ? currentVideo.id : 'default')"
                :src="currentVideo.videoUrl"
                :poster="currentVideo.coverImage"
                controls
                autoplay
                show-center-play-btn
                enable-play-gesture
                enable-progress-gesture
                vslide-gesture
                vslide-gesture-in-fullscreen
                picture-in-picture-mode="pop"
                object-fit="contain"
                @error="handleVideoError"
                @play="onVideoPlay"
                @pause="onVideoPause"
                @ended="onVideoEnded"
                @timeupdate="onTimeUpdate"
                class="video-player"
            ></video>
            <view class="current-video-info">
                <view class="video-title">{{currentVideo.title}}</view>
                <view class="video-meta" v-if="currentVideo.durationFormat">
                    <text class="duration">时长: {{currentVideo.durationFormat}}</text>
                    <text class="episode" v-if="currentVideo.episodeNumber">第{{currentVideo.episodeNumber}}集</text>
                </view>
                <view class="video-desc" v-if="currentVideo.description">{{currentVideo.description}}</view>
            </view>
        </view>
        
        <!-- 视频列表 -->
        <view class="video-list-container">
            <view class="list-header">
                <text class="header-title">课程目录</text>
                <text class="video-count">共{{videoList.length}}个视频</text>
            </view>
            
            <view class="video-list">
                <view 
                    class="video-item" 
                    v-for="(item, index) in videoList" 
                    :key="item.id"
                    :class="{ active: currentVideo && currentVideo.id === item.id }"
                    @click="playVideo(item)"
                >
                    <view class="item-left">
                        <text class="video-index">{{index + 1}}</text>
                        <view class="video-info">
                            <view class="item-title">{{item.title}}</view>
                            <view class="item-duration" v-if="item.durationFormat">{{item.durationFormat}}</view>
                        </view>
                    </view>
                    <view class="item-right">
                        <text class="icon-play iconfont icon-bofang"></text>
                    </view>
                </view>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-state" v-if="videoList.length === 0 && !loading">
                <image src="/static/images/empty_data.png" mode="aspectFit"></image>
                <text>暂无视频内容</text>
            </view>
            
            <!-- 加载状态 -->
            <view class="loading-state" v-if="loading">
                <view class="spinner"></view>
                <text>加载中...</text>
            </view>
        </view>
    </view>
</template>

<script>
import { getCourseVideos, getCourseDetail } from '@/api/store.js';

export default {
    data() {
        return {
            id: 0,
            loading: false,
            courseInfo: {
                id: 0,
                title: ''
            },
            videoList: [],
            currentVideo: null
        }
    },
    onLoad(options) {
        if (options.id) {
            this.id = options.id;
            this.courseInfo.title = decodeURIComponent(options.title || '课程视频');
            
            // 保存videoId用于加载后选择指定视频
            if (options.videoId) {
                this.videoId = options.videoId;
            }
            
            // 显示全局加载
            uni.showLoading({
                title: '加载课程中...',
                mask: true
            });
            
            // 并行加载数据
            Promise.all([
                this.loadCourseVideos(),
                this.getCourseDetail()
            ]).finally(() => { // 使用finally确保hideLoading总能执行
                uni.hideLoading();
            });
        }
    },
    methods: {
        // 提取的URL修复函数
        fixVideoUrl(url) {
            if (!url) return url;
            // 查找最后一个 "http" 实例，并从那里开始截取字符串
            const lastHttpIndex = url.lastIndexOf('http');
            if (lastHttpIndex > 0) {
                return url.substring(lastHttpIndex);
            }
            return url;
        },

        goBack() {
            uni.navigateBack();
        },
        
        // 获取课程详情
        getCourseDetail() {
            if (!this.id) return;
            
            getCourseDetail(this.id).then(res => {
                if (res.data) {
                    const productInfo = res.data.productInfo || res.data;
                    this.courseInfo = {
                        id: productInfo.id || 0,
                        title: productInfo.storeName || '未命名课程',
                        image: this.fixVideoUrl(productInfo.image) || '',
                        totalEpisodes: productInfo.totalEpisodes || 0,
                        updatedEpisodes: productInfo.updatedEpisodes || 0
                    };
                }
            }).catch(err => {
                console.error('获取课程详情失败', err);
            });
        },
        
        // 加载课程视频 - 修复URL处理
        loadCourseVideos() {
            if (!this.id) return Promise.resolve();
            
            this.loading = true;
            
            return new Promise((resolve, reject) => {
                getCourseVideos(this.id).then(res => {
                    this.loading = false;
                    
                    if (res.data && res.data.length > 0) {
                        const fixedVideos = res.data.map(video => {
                            video.videoUrl = this.fixVideoUrl(video.videoUrl);
                            video.coverImage = this.fixVideoUrl(video.coverImage);
                            return video;
                        });
                        
                        // 按集数顺序排序视频
                        this.videoList = fixedVideos.sort((a, b) => {
                            return (a.episodeNumber || 0) - (b.episodeNumber || 0);
                        });
                        
                        // 其他逻辑保持不变
                        if (this.videoId) {
                            const specifiedVideo = this.videoList.find(v => v.id == this.videoId);
                            this.currentVideo = specifiedVideo || this.videoList[0];
                        } else {
                            const lastWatchedId = uni.getStorageSync(`last_watched_${this.id}`);
                            const lastVideo = lastWatchedId ? this.videoList.find(v => v.id == lastWatchedId) : null;
                            this.currentVideo = lastVideo || this.videoList[0];
                        }
                        resolve();
                    } else {
                        resolve();
                    }
                }).catch(err => {
                    this.loading = false;
                    console.error('获取课程视频列表失败', err);
                    reject(err);
                });
            });
        },
        
        // 修复视频播放方法
        playVideo(video) {
            if (!video || (this.currentVideo && this.currentVideo.id === video.id)) {
                return;
            }
            
            uni.hideLoading();
            
            // 保存当前播放位置
            if (this.currentVideo) {
                try {
                    const videoContext = uni.createVideoContext('video-player-' + this.currentVideo.id, this);
                    const position = videoContext.currentTime || 0;
                    if (position > 0) {
                        uni.setStorageSync(`video_position_${this.currentVideo.id}`, position);
                    }
                } catch (e) {
                    console.log('保存播放位置失败');
                }
            }
            
            // 修复视频URL
            video.videoUrl = this.fixVideoUrl(video.videoUrl);
            
            // 更新当前视频
            this.currentVideo = video;
            
            // 滚动到顶部视频播放器区域
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 300
            });
            
            // 延迟一小段时间再操作视频，确保DOM已更新
            setTimeout(() => {
                try {
                    // 获取视频上下文并播放
                    const videoContext = uni.createVideoContext('video-player-' + video.id, this);
                    if (videoContext) {
                        videoContext.stop();
                        
                        // 尝试恢复上次播放位置
                        const lastPosition = uni.getStorageSync(`video_position_${video.id}`);
                        if (lastPosition > 10) {
                            uni.hideLoading();
                            uni.showModal({
                                title: '继续观看',
                                content: '是否从上次观看的位置继续播放？',
                                confirmText: '继续播放',
                                cancelText: '从头开始',
                                success: (res) => {
                                    if (res.confirm) {
                                        videoContext.seek(lastPosition);
                                    }
                                    videoContext.play();
                                }
                            });
                        } else {
                            videoContext.play();
                            uni.hideLoading();
                        }
                    } else {
                        uni.hideLoading();
                    }
                } catch (e) {
                    console.error('操作视频上下文出错:', e);
                    uni.hideLoading();
                }
            }, 300);
            
            // 记录观看历史
            this.saveViewHistory(video);
        },
        
        // 处理视频播放错误 - 简化错误处理
        handleVideoError(e) {
            console.error('视频播放错误:', e);
            uni.hideLoading();
        
            // 尝试修复URL并重试
            if (this.currentVideo && this.currentVideo.videoUrl) {
                const originalUrl = this.currentVideo.videoUrl;
                const fixedUrl = this.fixVideoUrl(originalUrl);
        
                if (originalUrl !== fixedUrl) {
                    this.currentVideo.videoUrl = fixedUrl;
                    
                    uni.showToast({
                        title: '正在尝试修复视频链接...',
                        icon: 'none',
                        duration: 2000
                    });
        
                    this.$nextTick(() => {
                        try {
                            const videoContext = uni.createVideoContext('video-player-' + this.currentVideo.id, this);
                            if (videoContext) {
                                videoContext.stop();
                                videoContext.play();
                            }
                        } catch (err) {
                            console.error('尝试重新加载视频失败', err);
                        }
                    });
                    return;
                }
            }
        
            // 一般错误处理
            let errorMsg = '视频加载失败，请重试';
            if (e.detail && e.detail.errMsg) {
                if (e.detail.errMsg.includes('network')) {
                    errorMsg = '网络错误，请检查网络连接';
                } else if (e.detail.errMsg.includes('format')) {
                    errorMsg = '视频格式不支持';
                } else if (e.detail.errMsg.includes('404')) {
                    errorMsg = '视频文件不存在或已被移除';
                } else if (e.detail.errMsg.includes('451')) {
                    errorMsg = '视频因法律原因不可用';
                }
            }
        
            uni.showToast({
                title: errorMsg,
                icon: 'none',
                duration: 3000
            });
        },
        
        // 添加新方法 - 保存观看历史
        saveViewHistory(video) {
            if (!video || !video.id) return;
            
            // 保存当前观看的视频ID
            uni.setStorageSync(`last_watched_${this.id}`, video.id);
            
            // 可以进一步记录观看进度、观看时间等信息
            const now = new Date().toISOString();
            const historyData = {
                courseId: this.id,
                videoId: video.id,
                title: video.title,
                lastWatchTime: now
            };
            
            try {
                let historyList = uni.getStorageSync('course_history') || [];
                historyList = Array.isArray(historyList) ? historyList : [];
                
                // 删除旧记录
                historyList = historyList.filter(item => !(item.courseId == this.id && item.videoId == video.id));
                
                // 添加新记录到最前面
                historyList.unshift(historyData);
                
                // 限制历史记录数量，最多保存50条
                if (historyList.length > 50) {
                    historyList = historyList.slice(0, 50);
                }
                
                uni.setStorageSync('course_history', historyList);
            } catch (e) {
                console.error('保存观看历史失败', e);
            }
        },
        
        // 添加视频播放事件处理
        onVideoPlay() {
            console.log('视频开始播放');
        },
        
        onVideoPause() {
            console.log('视频暂停');
            // 可以在这里保存播放进度
            if (this.currentVideo) {
                const videoContext = uni.createVideoContext('video-player-' + this.currentVideo.id, this);
                const position = videoContext.currentTime;
                uni.setStorageSync(`video_position_${this.currentVideo.id}`, position);
            }
        },
        
        onVideoEnded() {
            console.log('视频播放结束');
            // 可以在这里自动播放下一集
            const currentIndex = this.videoList.findIndex(v => v.id === this.currentVideo.id);
            if (currentIndex !== -1 && currentIndex < this.videoList.length - 1) {
                // 显示提示是否播放下一集
                uni.showModal({
                    title: '视频已播放完毕',
                    content: '是否自动播放下一集？',
                    confirmText: '自动播放',
                    cancelText: '停留当前',
                    success: (res) => {
                        if (res.confirm) {
                            this.playVideo(this.videoList[currentIndex + 1]);
                        }
                    }
                });
            }
        },
        
        onTimeUpdate(e) {
            // 每隔30秒自动保存一次播放进度
            const currentTime = e.detail.currentTime;
            if (Math.floor(currentTime) % 30 === 0 && currentTime > 0) {
                uni.setStorageSync(`video_position_${this.currentVideo.id}`, currentTime);
            }
        },
        
        // 开始学习
        startLearning() {
            // 跳转到课程视频页面
            uni.navigateTo({
                url: `/pages/course/xianshangkecheng/xianshangkecheng?id=${this.courseInfo.id}&title=${encodeURIComponent(this.courseInfo.title)}`
            });
        }
    }
}
</script>

<style lang="scss">
.course-video-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.nav-bar {
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 30rpx;
    background-color: #ffffff;
    
    .nav-left {
        font-size: 40rpx;
        color: #333;
    }
    
    .nav-title {
        flex: 1;
        font-size: 32rpx;
        color: #333;
        text-align: center;
        margin: 0 60rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.video-player-container {
    background-color: #000;
    
    .video-player {
        width: 100%;
        height: 422rpx;
    }
    
    .current-video-info {
        background-color: #fff;
        padding: 30rpx;
        
        .video-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 10rpx;
        }
        
        .video-meta {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 10rpx;
            
            .duration {
                margin-right: 10rpx;
            }
            
            .episode {
                margin-left: 10rpx;
            }
        }
        
        .video-desc {
            font-size: 26rpx;
            color: #666;
            line-height: 1.5;
        }
    }
}

.video-list-container {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    
    .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 20rpx;
        border-bottom: 1px solid #f0f0f0;
        
        .header-title {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;
        }
        
        .video-count {
            font-size: 24rpx;
            color: #999;
        }
    }
    
    .video-list {
        .video-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30rpx 0;
            border-bottom: 1px solid #f5f5f5;
            
            &.active {
                background-color: #f9f9f9;
                border-left: 4rpx solid #4a90e2;
                padding-left: 16rpx;
            }
            
            .item-left {
                display: flex;
                align-items: center;
                flex: 1;
                
                .video-index {
                    width: 50rpx;
                    font-size: 28rpx;
                    color: #999;
                    text-align: center;
                }
                
                .video-info {
                    flex: 1;
                    margin-left: 20rpx;
                    
                    .item-title {
                        font-size: 28rpx;
                        color: #333;
                        margin-bottom: 6rpx;
                    }
                    
                    .item-duration {
                        font-size: 24rpx;
                        color: #999;
                    }
                }
            }
            
            .item-right {
                .icon-play {
                    font-size: 40rpx;
                    color: #4a90e2;
                }
            }
        }
    }
    
    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 60rpx 0;
        
        image {
            width: 200rpx;
            height: 200rpx;
            margin-bottom: 20rpx;
        }
        
        text {
            font-size: 28rpx;
            color: #999;
        }
    }
    
    .loading-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 60rpx 0;
        
        .spinner {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
            border: 4rpx solid #f3f3f3;
            border-top: 4rpx solid #4a90e2;
            animation: spin 1s linear infinite;
            margin-bottom: 20rpx;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        text {
            font-size: 28rpx;
            color: #999;
        }
    }
}
</style>